package com.crx.springbootinit.common;

import cn.hutool.core.collection.CollUtil;
import com.crx.springbootinit.model.entity.Chat;
import com.crx.springbootinit.service.IChatService;
import com.crx.springbootinit.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 谢杭延
 * @Date 2024-10-24 13:59
 */
@ServerEndpoint("/imserver/{userId}")
@Component
@Slf4j
public class WebSocketServer {

    private IChatService chatService;
    private static ConcurrentHashMap<Long, WebSocketServer> webSocketMap = new ConcurrentHashMap<> ();
    private Long userId;
    private Session session;

    @OnOpen
    public void onOpen(Session session,@PathParam("userId") Long userId) throws IOException {
        this.userId=userId;
        this.session=session;
        webSocketMap.put(userId,this);
        chatService= SpringContextUtils.getBean(IChatService.class);
        //检查是否有未读消息，推送未读消息更新数据isRead字段
        List<Chat> unreadMessages=chatService.lambdaQuery().eq(Chat::getTargetId,userId).eq(Chat::getIsRead,false).list();
        if(CollUtil.isNotEmpty(unreadMessages)){
            for(Chat chat:unreadMessages){
                this.session.getBasicRemote().sendText(chat.getContent());
                chatService.lambdaUpdate()
                        .eq(Chat::getId,chat.getId())
                        .set(Chat::getIsRead, true).update();
            }
        }
    }

    @OnClose
    public void close() {
        webSocketMap.remove(userId);
        log.info("用户 " + userId + " 已断开");
    }

    public static Map<Long, WebSocketServer> getOnlineUser(){
        return webSocketMap;
    }

    public static Boolean sendInfo(Chat chat) throws IOException {
        WebSocketServer targetUser = webSocketMap.get(chat.getTargetId());
        if(targetUser!=null){
            targetUser.session.getBasicRemote().sendText(chat.getContent());
            return true;
        }
        return false;
    }

    public static void sendNotification(Long targetId, String content) throws IOException {
        WebSocketServer targetUser=webSocketMap.get(targetId);
        if(targetUser!=null){
            targetUser.session.getBasicRemote().sendText(content);
        }
    }


}
